package com.wpzf.zxhc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wpzf.zxhc.utils.OBSUploadUnits;
import com.wpzf.zxhc.mapper.AppMapper;
import com.wpzf.zxhc.service.AppService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class AppServiceImpl implements AppService {

    @Autowired
    AppMapper appMapper;


    @Override
    public List<Map<String, Object>> queryPch(Map<String, Object> param) {
        return appMapper.queryPch(param);
    }

    @Override
    public List<Map<String, Object>> queryXzqdmList(Map<String, Object> param) {
        return appMapper.queryXzqdmList(param);
    }

    @Override
    public Integer queryXzqdmListCount(Map<String, Object> param) {
        return appMapper.queryXzqdmListCount(param);
    }

    @Override
    public List<Map<String, Object>> queryDkTaskList(Map<String, Object> param) {
        return appMapper.queryDkTaskList(param);
    }

    @Override
    public Integer queryDkTaskListCount(Map<String, Object> param) {
        return appMapper.queryDkTaskListCount(param);
    }

    @Override
    public List<Map<String, Object>> queryProjectList(Map<String, Object> param) {
        return appMapper.queryProjectList(param);
    }

    @Override
    public Integer queryProjectListCount(Map<String, Object> param) {
        return appMapper.queryProjectListCount(param);
    }

    @Override
    public List<Map<String, Object>> queryTaskList(Map<String, Object> param) {
        return appMapper.queryTaskList(param);
    }

    @Override
    public Integer queryTaskListCount(Map<String, Object> param) {
        return appMapper.queryTaskListCount(param);
    }

    @Override
    public List<Map<String, Object>> queryTbList(Map<String, Object> param) {
        return appMapper.queryTbList(param);
    }

    @Override
    public Integer queryTbListCount(Map<String, Object> param) {
        return appMapper.queryTbListCount(param);
    }

    @Override
    public Map<String, Object> queryTbInfo(Map<String, Object> param) {
        return appMapper.queryTbInfo(param);
    }

    @Override
    public List<Map<String, Object>> queryWKT(Map<String, Object> param) {
        return appMapper.queryWKT(param);
    }

    @Override
    public Map<String, Object> getTaskDetailAnnex(Map<String, Object> param) {
        return appMapper.getTaskDetailAnnex(param);
    }

    @Override
    public Integer saveTaskDetailAnnex(Map<String, Object> param) {
        Integer rest = 0;
        Map<String, Object> map = getTaskDetailAnnex(param);
        if (map != null) {
            param.put("uuid", param.get("uuid"));
            param.put("modifier", param.get("username"));
            param.put("modifydate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
            rest = appMapper.updateTaskDetailAnnex(param);
        } else {
            param.put("creator", param.get("username"));
            param.put("createdate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
            String uuid = UUID.randomUUID().toString();
            param.put("uuid", uuid);
            rest = appMapper.saveTaskDetailAnnex(param);
        }
        return rest;
    }

    @Override
    public Integer updateFjInfo(Map<String, Object> param) {
        return appMapper.updateFjInfo(param);
    }

    @Override
    public Integer save(Map<String, Object> param) {
        param = (Map<String, Object>) param.get("mainData");
        return appMapper.save(param);
    }

    @Override
    public Integer delete(Map<String, Object> param) {
        return appMapper.delete(param);
    }

    @Override
    public Map<String, Object> queryTbxxbxj(Map<String, Object> param) {
        return appMapper.queryTbxxbxj(param);
    }

    @Override
    public List<Map<String, Object>> queryReTaskdetailAnnex(Map<String, Object> param) {
        return appMapper.queryReTaskdetailAnnex(param);
    }


    public String getInfo(Map<String, Object> param) {
//        Map<String, Object> param = new HashMap<>();
//        param.put("tbbh", "533123S120240109SC00005-1");
//        param.put("pch", "2024S10322wpys");
//        param.put("xzqdm", "533123");

//        String tbbh = param.get("tbbh") + "";
//        if (tbbh.indexOf("-") != -1) {
//            String jcbh = tbbh.substring(0, tbbh.indexOf("-"));
//            param.put("jcbh", jcbh);
//        } else {
//            param.put("jcbh", tbbh);
//        }

        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> dataList = new ArrayList<>();
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> main = new HashMap<>();
        Map<String, Object> wpzfdk = new HashMap<>();
        Map<String, Object> tbxxbxj = queryTbxxbxj(param);
        wpzfdk.put("tbbsm", "");
        wpzfdk.put("tbbh", "");
        wpzfdk.put("dkbh", "");
        wpzfdk.put("sjtbmj", "");
        wpzfdk.put("jcrq", "");
        wpzfdk.put("xzqdm", "");
        wpzfdk.put("tbfl", "");
        wpzfdk.put("xzmc", "");
        wpzfdk.put("csmc", "");
        wpzfdk.put("xxdz", "");
        wpzfdk.put("geometry", tbxxbxj.get("wkt"));
        wpzfdk.put("dlrdnydmj", "");
        wpzfdk.put("dlrdgdmj", "");
        wpzfdk.put("yjjbntmj", "");
        wpzfdk.put("wsx_dlrdstmj", "");
        wpzfdk.put("stbhhxmj", "");
        wpzfdk.put("hcjl", "");
        wpzfdk.put("tblx", "");
        wpzfdk.put("sjyt", "");
        wpzfdk.put("sjyt2", "");
        wpzfdk.put("hfsjyt", "");
        wpzfdk.put("hfpdyjsm", "");
        wpzfdk.put("nydmj", "");
        wpzfdk.put("gdmj", "");
        wpzfdk.put("stmj", "");
        wpzfdk.put("sjdkmj", "");
        wpzfdk.put("tb_stbhhxmj", "");
        wpzfdk.put("wflx1", "");
        wpzfdk.put("wflx2", "");
        wpzfdk.put("wflx3", "");
        wpzfdk.put("wflx4", "");
        wpzfdk.put("lzgdjf", "");
        wpzfdk.put("sywhzj", "");
        wpzfdk.put("sfdpf", "");
        wpzfdk.put("wfsjyt", "");
        wpzfdk.put("wfpdyjsm", "");
        wpzfdk.put("sfjsyd", "");
        wpzfdk.put("tbjsqk", "");
        wpzfdk.put("wf_xmmc", "");
        wpzfdk.put("wf_xmzt", "");
        wpzfdk.put("wf_xmlx", "");
        wpzfdk.put("wf_lxpzjg", "");
        wpzfdk.put("wf_lxpzwh", "");
        wpzfdk.put("wf_clfs", "");
        wpzfdk.put("sfylwsss", "");
        wpzfdk.put("sfbzxajzf", "");
        wpzfdk.put("sfjjxm", "");
        wpzfdk.put("wf_labh", "");
        wpzfdk.put("yjbm", "");
        wpzfdk.put("zglsdwqk", "");
        wpzfdk.put("fgymmj", "");
        wpzfdk.put("fgdwmj", "");
        wpzfdk.put("ccfg_yjjbnt", "");
        wpzfdk.put("ccfg_stbhq", "");
        wpzfdk.put("fgysdw", "");
        wpzfdk.put("fgysfzr", "");
        wpzfdk.put("qtydsjyt", "");
        wpzfdk.put("qtydsjyt2", "");
        wpzfdk.put("pwsj", "");
        wpzfdk.put("qtpdyjsm", "");

        Map<String, Object> other = new HashMap<>();
        List<Map<String, Object>> hcfjList = new ArrayList<>();
        List<Map<String, Object>> reTaskdetailAnnexList = queryReTaskdetailAnnex(param);
        for (Map<String, Object> reTaskdetailAnnex : reTaskdetailAnnexList) {
            String fj = reTaskdetailAnnex.get("fj") + "";
            if (fj.indexOf("jpg") != -1) {
                Map<String, Object> hcfj = new HashMap<>();
                hcfj.put("bsm", "");
                hcfj.put("xzqdm", "");
                hcfj.put("tbbsm", "");
                hcfj.put("tbbh", "");
                hcfj.put("fjmc", reTaskdetailAnnex.get("fjmc"));
                hcfj.put("lysb", "");
//                hcfj.put("fjlx", "IMAGE");
                hcfj.put("fjlx", reTaskdetailAnnex.get("fjlx"));
                hcfj.put("psry", reTaskdetailAnnex.get("psry"));
                hcfj.put("pssj", reTaskdetailAnnex.get("pssj"));
                hcfj.put("longitude", reTaskdetailAnnex.get("longitude"));
                hcfj.put("latitude", reTaskdetailAnnex.get("latitude"));
                hcfj.put("psjd", reTaskdetailAnnex.get("psjd"));
                hcfj.put("psgd", reTaskdetailAnnex.get("psgd"));
                hcfj.put("psfyj", reTaskdetailAnnex.get("psfyj"));
                hcfj.put("psaltitude", reTaskdetailAnnex.get("psaltitude"));
                hcfj.put("takeofflon", "");
                hcfj.put("takeofflat", "");
                hcfj.put("takeoffrelheight", "");
                hcfj.put("takeoffaltitude", "");
                hcfj.put("metarecord", "");
                hcfj.put("arg", "");
                hcfj.put("url", reTaskdetailAnnex.get("fj"));

                hcfj.put("creator", reTaskdetailAnnex.get("creator"));
                hcfj.put("xzb", reTaskdetailAnnex.get("xzb"));
                hcfj.put("yzb", reTaskdetailAnnex.get("yzb"));
                hcfj.put("ower_lever", reTaskdetailAnnex.get("ower_lever"));
                hcfj.put("uuid", reTaskdetailAnnex.get("uuid"));
                hcfj.put("dkbh", reTaskdetailAnnex.get("dkbh"));

                hcfjList.add(hcfj);
            }
        }


        other.put("pwinfo", new ArrayList<>());
        other.put("fjinfo", new ArrayList<>());
        other.put("hcfj", hcfjList);
        data.put("other", other);
        main.put("wpzfdk", wpzfdk);
        data.put("main", main);
        dataList.add(data);
        map.put("data", dataList);
        JSONObject jsonObject = new JSONObject(map);
        System.out.println(jsonObject.toJSONString());
        return jsonObject.toJSONString();
    }

    @Override
    public List<Map<String, Object>> getFlieInfo(Map<String, Object> param) {
        return appMapper.getFlieInfo(param);
    }

    @Override
    public List<String> getPch(Map<String, Object> param) {
        return appMapper.getPch(param);
    }

    @Override
    public List<Map<String, Object>> queryTaskTbList(Map<String, Object> param) {
        return appMapper.queryTaskTbList(param);
    }

    @Override
    public Integer queryTaskTbListCount(Map<String, Object> param) {
        return appMapper.queryTaskTbListCount(param);
    }

    @Override
    public Map<String, Object> queryTbDetails(Map<String, Object> param) {
        Map<String, Object> rest = new HashMap<>();
        rest.put("dkInfo", appMapper.queryDkInfo(param));
        List<Map<String, Object>> annexList = appMapper.queryAnnexList(param);
        rest.put("annexList", annexList);
        rest.put("wyms", appMapper.queryWyms(param));
        rest.put("status", annexList != null ? 1 : 0);
        return rest;
    }

    @Override
    public List<Map<String, Object>> getFileStreamById(Map<String, Object> param) throws IOException {
        List<String> uuidList = (List<String>) param.get("uuidList");
        List<Map<String, Object>> rest = new ArrayList<>();
        for (String uuid : uuidList) {
            Map<String, Object> map = new HashMap<>();
            map.put("uuid", uuid);
            Map<String, Object> annex = appMapper.queryAnnexById(uuid);
            String fj = annex.get("fj") + "";


            URL url = new URL(fj);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);

            InputStream inputStream = new BufferedInputStream(connection.getInputStream());
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            inputStream.close();
            connection.disconnect();

            byte[] binaryData = outputStream.toByteArray();
            // 使用Base64编码将二进制数据转换为字符串
            String binaryString = Base64.getEncoder().encodeToString(binaryData);
            map.put("base64", binaryString);
            rest.add(map);
        }

        return rest;
    }

    @Override
    @Transactional
    public String saveInfo(Map<String, Object> param) throws IOException {
        Integer deleteCount = 0;
        Integer saveCount = 0;
        Integer wymsCount = 0;

        List<Map<String, Object>> deleteAnnexList = (List<Map<String, Object>>) param.get("deleteAnnexList");
        if (deleteAnnexList != null && deleteAnnexList.size() > 0) {
            for (Map<String, Object> deleteAnnex : deleteAnnexList) {
                deleteAnnex.put("modifyid", param.get("userId"));
                deleteAnnex.put("modifier", param.get("userName"));
                deleteAnnex.put("modifydate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
                Integer i = appMapper.deleteAnnex(deleteAnnex);
                if (i > 0) {
                    deleteAnnex.put("user_id", param.get("userId"));
                    deleteAnnex.put("user_name", param.get("userName"));
                    deleteAnnex.put("nick_name", param.get("nickName"));
                    deleteAnnex.put("submitdate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
                    deleteCount += appMapper.saveAnnexDeleteLog(deleteAnnex);
                }

            }
        }

        List<Map<String, Object>> saveAnnexList = (List<Map<String, Object>>) param.get("saveAnnexList");
        if (saveAnnexList != null && saveAnnexList.size() > 0) {
            for (Map<String, Object> saveAnnex : saveAnnexList) {

                String fjmc = saveAnnex.get("fjmc") + "";
                String pch = saveAnnex.get("pch") + "";
                String xzqdm = saveAnnex.get("xzqdm") + "";
                String dkbh = saveAnnex.get("dkbh") + "";

                String OBSAddress = "app" + "/" + pch + "/" + xzqdm + "/" + dkbh + "/" + fjmc;
                String fj = "https://obs-top.obs.cn-north-1.myhuaweicloud.com/" + OBSAddress;
                saveAnnex.put("fj", fj);

                String log = null;
                if (saveAnnex.get("base64") != null && !((String) saveAnnex.get("base64")).isEmpty()) {
                    String base64 = saveAnnex.get("base64") + "";
                    String path = System.getProperty("user.dir") + "\\" + "appFiles" + "\\" + pch + "\\" + xzqdm + "\\" + dkbh;
                    File folder = new File(path);
                    // 判断路径是否存在,不存在则自动创建
                    if (!folder.exists()) {
                        folder.mkdirs();
                    }

                    String outputFilePath = path + "\\" + fjmc;

                    byte[] decodedBytes = Base64.getDecoder().decode(base64);
                    File outputFile = new File(outputFilePath);
                    FileOutputStream outputStream = new FileOutputStream(outputFile);
                    outputStream.write(decodedBytes);
                    outputStream.close();

                    System.out.println("文件已成功下载到本地: " + outputFilePath);

                    AtomicInteger attemptCount = new AtomicInteger(0);

                    do {
                        log = OBSUploadUnits.OBSUpload(OBSAddress, outputFilePath);
                        attemptCount.incrementAndGet();
                    } while (!log.equals("success") && attemptCount.get() < 5);

                    File file = new File(outputFilePath);
                    if (file.exists()) {
                        if (file.isFile()) {
                            file.delete();
                            System.out.println("文件删除成功：" + outputFilePath);
                        }
                    } else {
                        System.out.println("文件不存在：" + outputFilePath);
                    }
                }


                if ("success".equals(log) || saveAnnex.get("base64") == null || ((String) saveAnnex.get("base64")).isEmpty()) {
                    saveAnnex.put("uuid", UUID.randomUUID().toString());
                    saveAnnex.put("createid", param.get("userId"));
                    saveAnnex.put("creator", param.get("userName"));
                    saveAnnex.put("createdate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));
                    //保存附件信息
                    saveCount += appMapper.saveAnnex(saveAnnex);
                } else {
                    return "OBS多次尝试上传文件仍然失败：" + log;
                }
            }
        }

        List<Map<String, Object>> wymsInfoList = (List<Map<String, Object>>) param.get("wymsInfoList");
        if (wymsInfoList != null && wymsInfoList.size() > 0) {
            for (Map<String, Object> wymsInfo : wymsInfoList) {
                wymsInfo.put("creatorid", param.get("userId"));
                wymsInfo.put("creator", param.get("userName"));
                wymsInfo.put("submitdate", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime()));

                appMapper.deleteAnnexWysm(wymsInfo);
                wymsCount = appMapper.saveAnnexWysm(wymsInfo);
            }
        }

        return "保存信息：" + saveCount + "，删除信息：" + deleteCount + "，外业描述保存：" + wymsCount;
    }

    @Override
    public String getVersion(Map<String, Object> param) {
        return appMapper.getVersion(param);
    }

    @Override
    @Transactional
    public Integer updateVersion(Map<String, Object> param) {
        appMapper.deleteVersion(param);
        return appMapper.updateVersion(param);
    }

    @Override
    public Integer saveLog(Map<String, Object> param) {
        return appMapper.saveLog(param);
    }

}
